import React, {useRef, useState, useEffect} from 'react';
import {connect, history} from 'umi';
import {cloneDeep} from 'lodash';
import moment from 'moment';
import request from '@/utils/request'
import {ActionType, PageContainer, ProTable} from '@ant-design/pro-components';
import {Button, Modal, message, Form, DatePicker, Input, Switch, InputNumber, Tag, Select} from 'antd';
import {PlusOutlined} from '@ant-design/icons';
import 'moment/locale/zh-cn';
moment.locale('zh-cn')


const {TextArea} = Input;
const { RangePicker } = DatePicker;


const TableList: React.FC<unknown> = (props: any) => {
    // console.log('urlA', urlA)
    const {dispatch} = props;
    const [form] = Form.useForm();
    const actionRef = useRef<ActionType>();
    const [formModalOpen, setFormOpen] = useState(false);
    const [stationList, setList] = useState([]);
    const [carList, setCarList] = useState([]);
    useEffect(() => {
        // dispatch({
        //     type: 'files/init'
        // })
        request('/api1/baseFunction/stationPageList', {
            method: 'post',
            data: {
                pageNum: 1,
                pageSize: 9999
            }
        }).then((res) => {
            console.log('全部站', res);
            if (res && res.code === 200){
                setList(res?.data?.records || [])
            }
        });
        request('/api1/baseFunction/carPageList', {
            method: 'post',
            data: {
                pageNum: 1,
                pageSize: 9999
            }
        }).then((res) => {
            console.log('全部站', res);
            if (res && res.code === 200){
                setCarList(res?.data?.records || [])
            }
        });
        if (form){
            form.setFieldValue('stationName', '')
        }
    }, [dispatch]);
    const hideFileModal = () => {
        setFormOpen(false);
        form.resetFields();
    }
    const submitFileForm = (values: any) => {
        console.log('submitFileForm', values);
        const OBJ = {
            ...values,
            residualCapacity: values.residualCapacity ? values.residualCapacity * 1000 : 0,
            beginTime: values.effectTime2[0] ? moment(values.effectTime2[0]).format('YYYY-MM-DD 00:00:00') : '',
            endTime: values.effectTime2[1] ? moment(values.effectTime2[1]).format('YYYY-MM-DD 23:59:59') : '',
        };
        console.log('OBJ', OBJ);
        delete OBJ.effectTime;
        delete OBJ.effectTime2;
        // // if (form.v)
        request(
            '/api1/monitorDevice/insertVin',
            {
                method: 'POST',
                // requestType: 'form',
                data: {
                    ...OBJ
                },
            }
        ).then((response) => {
            if (response && response.code === 200) {
                message.success('新增成功');
                if (actionRef.current) {
                    actionRef.current.reload();
                    setFormOpen(false);
                    form.resetFields();
                }
            } else {
                message.warning(response?.msg)
            }
        })
    }
    function size(bytes: any) {
        if (bytes >= 10000) {
            bytes = (bytes / 10000).toFixed(2) + " 万度";
        } else {
            bytes = parseFloat(bytes) <= 0 ? 0 : parseFloat(bytes).toFixed(2) + " 度";
        }
        return bytes;
    }
    const onCarChange = (value, option) => {
        console.log('onCarChange', value)
        console.log('onCarChangeoption', option);
        if (value){
            form.setFieldValue('carCode', option?.label)
        }
    }
    const onStationChange = (value, option) => {
        console.log('onStationChange', value)
        console.log('onStationChangeOpt', option);
        if (value){
            form.setFieldValue('stationName', option?.label)
        }
    }
    const stationEnum: any = {};
    if (stationList && stationList.length){
        for (const d of stationList){
            stationEnum[parseInt(d.id)] = {text: d.stationName}
        }
    }
    const columns: any = [
        {
            title: '车牌号',
            dataIndex: 'carCode',
            // tip: '名称是唯一的 key',
        },
        {
            title: '车辆vin',
            dataIndex: 'vin',
            // tip: '名称是唯一的 key',
        },
        {
            title: '适用场站',
            dataIndex: 'stationId',
            // tip: '名称是唯一的 key',
            valueEnum: stationEnum,
            render: (_, record) => {
                return (<span>{record?.stationName || ''}</span>)
            }
        },
        {
            title: '包时电量',
            dataIndex: 'initCapacity',
            search: false,
            render: (text, record) => {
                return (
                    <span>{size(text)}</span>
                )
            }
        },
        {
            title: '已用电量',
            dataIndex: 'residualCapacity2',
            search: false,
            render: (text, record) => {
                return (
                    <span>{size(record?.initCapacity - record?.residualCapacity)}</span>
                )
            }
        },
        {
            title: '剩余电量',
            dataIndex: 'residualCapacity',
            search: false,
            render: (text, record) => {
                return (
                    <span>{size(text)}</span>
                )
            }
        },
        {
            title: '生效时间',
            dataIndex: 'effectTime',
            search: false,
            render: (text, record) => {
                return (
                    <span>{`${moment(record?.beginTime).format('YYYY.MM.DD')} -- ${moment(record?.endTime).format('YYYY.MM.DD')}`}</span>
                )
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            search: false,
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'text',
            // search: false,
            valueEnum: {
                0: {text: '启用'},
                1: {text: '停用'},
            },
            render: (text, record) => {
                // console.log('record', record);
                return (
                    <div>
                        {/*{record?.status ? <Tag color="green">启用</Tag> : <Tag color="#d9d9d9">停用</Tag>}*/}
                        <Switch
                            checked={record?.status === 0}
                            onChange={(checked) => {
                                console.log('checked', checked);
                                request(
                                    '/api1/monitorDevice/updateVin',
                                    {
                                        method: 'post',
                                        data: {
                                            id: record?.id,
                                            status: record?.status ? 0 : 1
                                        }
                                    }).then((response) => {
                                    console.log('停用启用', response);
                                    if (response.code && response.code === 200){
                                        message.success(record?.status ? '启用成功' : '停用成功');
                                        actionRef.current?.reload();
                                    }
                                })
                            }}
                            checkedChildren="启用"
                            unCheckedChildren="停用"
                        />
                    </div>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'ope',
            search: false,
            render: (_, record) => {
                return (
                    <a
                        onClick={() => {
                            // history.push('/order/chargeOrder', {
                            //     vin: record.vin,
                            //     startTime: record.beginTime,
                            //     endTime: record.endTime,
                            // })
                            dispatch({
                                type: 'order/setState',
                                payload: {
                                    searchState: {
                                        vin: record.vin,
                                        startTime: record.beginTime,
                                        endTime: record.endTime,
                                        pageNum: 1,
                                        pageSize: 10
                                    }
                                }
                            });
                            setTimeout(() => {
                                history.push('/order/chargeOrder')
                            }, 500)
                        }}
                    >订单记录</a>
                )
            }
        },
    ];
    return (
        <PageContainer
            header={{
                title: '',
            }}
        >
            <ProTable<API.UserInfo>
                headerTitle="包时列表"
                actionRef={actionRef}
                pagination={{defaultPageSize: 10}}
                rowKey="id"
                search={{
                    labelWidth: 120,
                    defaultCollapsed: false
                }}
                request={async (params, sorter, filter) => {
                    // const { data, success } = await queryUserList({
                    //   ...params,
                    //   // FIXME: remove @ts-ignore
                    //   // @ts-ignore
                    //   sorter,
                    //   filter,
                    // });
                    // return {
                    //   data: data?.list || [],
                    //   success,
                    // };
                    const cloneParams = cloneDeep(params);
                    delete cloneParams.current;
                    const {data, code} = await request('/api1/monitorDevice/vinPageList', {
                        method: 'post',
                        data: {
                            ...cloneParams,
                            stationId: parseInt(cloneParams?.stationId),
                            pageNum: params.current
                        }
                    });
                    if (code && code === 200) {
                        return {
                            data: data?.records || [],
                            success: true,
                            total: data?.total
                        };
                    }
                }}
                columns={columns}
            />
            <Modal
                title="新增包时设置"
                open={formModalOpen}
                width={680}
                onOk={form.submit}
                onCancel={hideFileModal}
                maskClosable={false}
                okText="确认"
                cancelText="取消"
            >
                <Form
                    labelCol={{span: 4}}
                    wrapperCol={{span: 14}}
                    layout="horizontal"
                    form={form}
                    style={{maxWidth: 600}}
                    onFinish={(values) => submitFileForm(values)}
                >
                    <Form.Item
                        label="vin"
                        name="carCode"
                        style={{display: 'none'}}
                    >
                    </Form.Item>
                    <Form.Item
                        label="车牌号"
                        name="vin"
                        rules={[{required: true, message: '请选择车辆'}]}
                    >
                        {/*<Input placeholder='请输入车辆vin' />*/}
                        <Select
                            showSearch
                            placeholder="请选择车辆"
                            optionFilterProp="label"
                            onChange={onCarChange}
                            // onSearch={onSearch}
                            options={
                                carList.length ?
                                    carList.map((i) => {return {value: i.vin, label: i.carCode}}) : []
                            }
                        />
                    </Form.Item>
                    <Form.Item
                        label="stationName"
                        name="stationName"
                        style={{display: 'none'}}
                    >
                    </Form.Item>
                    <Form.Item
                        label="适用场站"
                        name="stationId"
                        rules={[{required: false, message: '请选择场站'}]}
                    >
                        <Select
                            showSearch
                            placeholder="请选择场站"
                            optionFilterProp="label"
                            onChange={onStationChange}
                            // onSearch={onSearch}
                            options={
                                stationList.length ?
                                    stationList.map((i) => {return {value: i.id, label: i.stationName}}) : []
                            }
                        />
                    </Form.Item>
                    <Form.Item
                        name="effectTime2"
                        label="生效时间"
                        style={{display: 'none'}}
                    ></Form.Item>
                    <Form.Item
                        name="effectTime"
                        label="生效时间"
                        rules={[{required: true, message: '请选择升级时间'}]}
                    >
                        <RangePicker
                            style={{width: '350px'}}
                            // showTime
                            // disabledDate={(current: any) => {
                            //     return current < moment().subtract(1, 'days').endOf('days');
                            // }}
                            // disabledTime={disabledTime}
                            onChange={(_, dateStr) => {
                                console.log('dateStr', dateStr);
                                console.log('dateStr', moment(dateStr));
                                form.setFieldValue('effectTime2', [moment(dateStr[0]), moment(dateStr[1])])
                            }}
                        />
                    </Form.Item>
                    <Form.Item
                        label="包时电量"
                        name="residualCapacity"
                        rules={[{required: true, message: '请输入包时可用电量'}]}
                    >
                        <InputNumber placeholder='请输入包时可用电量' suffix="度" style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item
                        name="remark"
                        label="备注"
                        rules={[{required: false, message: ''}]}
                    >
                        <TextArea style={{width: '350px'}}/>
                    </Form.Item>
                </Form>
            </Modal>
        </PageContainer>
    );
};

export default connect(({files}) => {
    return {...files}
})(TableList);
